package com.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.config.PasswordConfig;
import com.leyou.dto.UserDTO;
import com.leyou.entity.User;
import com.leyou.mapper.UserMapper;
import com.leyou.myException.LyException;
import com.leyou.service.UserService;
import com.leyou.utils.RegexUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.leyou.constants.MQConstants.ExchangeConstants.*;
import static com.leyou.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

/**
 * @author jshstart
 * @creat 2020-12-22 16:46
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    private static final String KEY_PREFIX = "user:verify:code:phone:";

    /**
     * 判断用户是否存在
     * @param data
     * @param type
     * @return
     */
    @Override
    public Boolean isUserExists(String data, Integer type) {
        if (type!=1&&type!=2){
            throw  new LyException(403,"数据有误");
        }
        boolean isExists = query().eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count().equals(1);
        return isExists;
    }

    /**
     * 向mq发送消息，调用sms发送短信
     * @param phone
     */
    @Override
    public void sendMessage(String phone) {
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(403,"手机号不正确");
        }
        //生成一个随机的验证码
        String code = RandomStringUtils.randomNumeric(6);
        System.out.println("code = " + code);
        //存入redis
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
        //向mq发送消息，请求sms微服务发送短信
        HashMap<String, String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,map);
    }

    /**
     * 用户注册
     * @param user
     * @param code
     */
    @Override
    public void registerUser(User user, String code) {
        //1.校验验证码
        String redisCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code,redisCode)){
            throw new LyException(403,"验证码错误");
        }
        //2.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
    }

    /**
     * 根据用户名密码返回用户信息
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserDTO queryUserByNamePassword(String username, String password) {
        User user = query().eq("username", username).one();
        if (user==null){
            throw new LyException(400,"没有此用户");
        }
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"密码错误");
        }
        return new UserDTO(user);
    }


}